package com.pansky.crm.util;

import com.pansky.crm.constants.CommonConstant;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class TokenUtil {
    private static final String secret = "eyJhbGciOiJIUzI1NiJ9";//todo token加密salt盐值
    public static final String TOKEN_HEARD = "token";

    public static String getToken(String name, String id, String ip) {
        log.info("---getToken name:{},id:{},ip:{}", name, id, ip);
        JwtBuilder builder = Jwts.builder();
        builder.signWith(SignatureAlgorithm.HS256, secret);
        builder.setId(id).setSubject(name).setAudience(ip);
        builder.setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + CommonConstant.EXPIRE_TIME_SECOND * 1000));
        return builder.compact();
    }

    public static Claims getTokenBody(String token) {
        JwtParser parser = Jwts.parser();
        return parser.setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static String getName(String token) {
        Claims body = getTokenBody(token);
        String id = body.getId();
        return id;
    }

    /**
     * 刷新 token的过期时间
     */
    public static String refreshTokenExpired(String token) {
        JwtParser parser = Jwts.parser();
        Claims body = parser.setSigningKey(secret).parseClaimsJws(token).getBody();
        JwtBuilder builder = Jwts.builder();
        builder.signWith(SignatureAlgorithm.HS256, secret);
        builder.setId(body.getId()).setSubject(body.getSubject()).setAudience(body.getAudience());
        builder.setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + CommonConstant.EXPIRE_TIME_SECOND * 1000));
        return builder.compact();
    }

}